/*
 * Copyright (C) 2015-2020 Alibaba Group Holding Limited
 */
#include <string.h>
#include <board_part_opt.h>
#include <mtd_tiny.h>


int board_get_partition(uint32_t addr, uint32_t len, hal_partition_t* no, uint32_t* offset)
{
    hal_partition_t index = 0;
    hal_logic_partition_t *partition;

    for (index = 0; index < HAL_PARTITION_MAX; index++) {
        partition = board_get_info(index);
        if (partition == NULL) {
            continue;
        }

        if ((addr >= partition->partition_start_addr) &&
            (addr < (partition->partition_start_addr + partition->partition_length)) &&
            ((addr + len - 1) >= partition->partition_start_addr) &&
            ((addr + len - 1) < (partition->partition_start_addr + partition->partition_length))) {

            *no = index;
            *offset = addr - partition->partition_start_addr;
            return 0;
        }
    }

    return -1;
}

int board_read_data(unsigned int addr, unsigned char *buffer, unsigned int len)
{
    int      ret = 0;
    uint32_t offset = 0;

    hal_partition_t index;

    ret = board_get_partition(addr, len, &index, &offset);
    if (ret != 0) {
        return -1;
    }

    return mtd.read(index, &offset, (void *)buffer, len);
}

int board_write_data(unsigned int addr, unsigned char *buffer, unsigned int len)
{
    int      ret = 0;
    uint32_t offset = 0;

    hal_partition_t index;

    ret = board_get_partition(addr, len, &index, &offset);
    if (ret != 0) {
        return -1;
    }

    return mtd.write(index, &offset, (const void *)buffer, len);
}

int board_erase(unsigned int addr,  unsigned int size)
{
    int      ret = 0;
    uint32_t offset = 0;

    hal_partition_t index;

    ret = board_get_partition(addr, size, &index, &offset);
    if (ret != 0) {
        return -1;
    }

    return mtd.erase(index, offset, size);
}